package com.hth.stockspiderv3;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hth.stockspiderv3.po.StockBlock;
import com.hth.stockspiderv3.po.StockCallAuctionInfo;
import com.hth.stockspiderv3.po.StockInfo;
import com.hth.stockspiderv3.vo.KLineParseVo;
import com.hth.stockspiderv3.vo.PanKouInfoVo;
import com.hth.stockspiderv3.vo.StockBasicVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
//import sun.misc.IOUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.GZIPInputStream;


@Data
@Slf4j
public class HttpHandler {

    public static String doGet(String postUrl, String postData, Map<String, String> headers) {
        BufferedReader in = null;
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36 Edg/107.0.1418.42");
            conn.setRequestProperty("Accept-Charset", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            conn.setRequestProperty("Cookie", "qgqp_b_id=ebc1762f9c4ab91877ca3dfec2302b24; st_si=53084701262155; st_asi=delete; wap_ck1=true; wap_ck2=true; st_pvi=27729993858983; st_sp=2022-11-23%2015%3A42%3A08; st_inirUrl=https%3A%2F%2Fwap.eastmoney.com%2F; st_sn=4; st_psi=20221123154846721-113200301321-4806866114");
            conn.setRequestProperty("Host", "5.push2.eastmoney.com");
            conn.setConnectTimeout(7000);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            if (!StringUtils.isEmpty(postData)) {
                conn.setRequestProperty("Content-Length", "" + postData.length());
            } else {
                conn.setRequestProperty("Content-Length", "" + 0);
            }

            /**
             * 添加header信息
             */
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    conn.setRequestProperty(key, headers.get(key));
                }
            }
            if (!StringUtils.isEmpty(postData)) {
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                out.write(postData);
                out.flush();
                out.close();
            }
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.info("connect failed! respCode:{}|respMsg:{}", conn.getResponseCode(), conn.getResponseMessage());
                return "";
            }
            //获取响应内容体
            StringBuffer sb = new StringBuffer();
            String readLine = new String();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine).append("\n");
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("doPost Http failed! " + e.getMessage());
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("sendGet close Exception:" + e2.getMessage());
            }
        }

        return "";
    }


    /**
     * 向指定 URL 发送POST方法的请求
     */
    public static String sendJsonPost(String postUrl, String code) {
        String result = "";
        String jsonData = "[{\"logicalOperator\":\"and\",\"groupname\":\"groupname2\",\"subgroupname\":\"groupname0879200774654465\",\"rowlevel\":\"0\",\"conditionFieldVal\":\"dt\",\"conditionOptionVal\":\"greater_than\",\"conditionValueVal\":{\"value\":\"-200\",\"text\":\"-200\"},\"conditionValueLeftVal\":{\"value\":\"\",\"text\":\"\"},\"conditionValueRightVal\":{\"value\":\"\",\"text\":\"\"}},{\"logicalOperator\":\"and\",\"groupname\":\"groupname2\",\"subgroupname\":\"groupname4294845034540429\",\"rowlevel\":\"0\",\"conditionFieldVal\":\"stock\",\"conditionOptionVal\":\"equal\",\"conditionValueVal\":{\"value\":\"hth\",\"text\":\"hth\"},\"conditionValueLeftVal\":{\"value\":\"\",\"text\":\"\"},\"conditionValueRightVal\":{\"value\":\"\",\"text\":\"\"}}]".replace("hth", code);
        Map<String, String> param = Maps.newHashMap();
        param.put("page", "1");
        param.put("limit", "200");
        param.put("jsonStr", jsonData);
        param.put("csrfmiddlewaretoken", "OC16LAAquGsFWmfGyC2eXKy6HIUFX0oa6V9SSEwkA2lwJ6ZLRztGrYIgsEgw7t2A");
        param.put("sortField", "dt");
        param.put("sortOrder", "desc");
        param.put("groupsortField", "op");
        param.put("groupsortOrder", "desc");
        param.put("groupCount", "1");

        BufferedReader in = null;
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36 Edg/107.0.1418.42");
            conn.setRequestProperty("Accept-Charset", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            conn.setRequestProperty("Cookie", "sessionid=sk8m0jdrr9opc17osvwqkjvqmg5chszk; csrftoken=qCwnZ4Qk8fxgXjpYrL7BJPEXzsawLamZIVE968MeeBq7K393KIy3d3O7kownVD0p; __51uvsct__Jds6cWFcjStxRUTp=1; __51vcke__Jds6cWFcjStxRUTp=4aa2d7c2-bb5e-5cc9-a5e2-d8e86f85da62; __51vuft__Jds6cWFcjStxRUTp=1680328424533; __51huid__JduLwqNuBAhL1zpA=0766bc46-ec7f-57e8-ab1d-ca0d73dd484d; __vtins__Jds6cWFcjStxRUTp=%7B%22sid%22%3A%20%22a0b2052a-3761-5abd-8fbc-017299d3f867%22%2C%20%22vd%22%3A%203%2C%20%22stt%22%3A%2078148%2C%20%22dr%22%3A%2039329%2C%20%22expires%22%3A%201680330302678%2C%20%22ct%22%3A%201680328502678%7D");
            conn.setRequestProperty("Host", "mygu588.cn");
            conn.setRequestProperty("Origin", "https://mygu588.cn");
            conn.setRequestProperty("Referer", "https://mygu588.cn/vipquery/");
            conn.setConnectTimeout(7000);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            if (!StringUtils.isEmpty(jsonData)) {
                conn.setRequestProperty("Content-Length", "" + jsonData.length());
            } else {
                conn.setRequestProperty("Content-Length", "" + 0);
            }

            /**
             * 添加header信息
             */
//            if (headers != null && headers.size() > 0) {
//                for (String key : headers.keySet()) {
//                    conn.setRequestProperty(key, headers.get(key));
//                }
//            }
            jsonData = "page=1&limit=200&jsonStr=[{\"logicalOperator\":\"and\",\"groupname\":\"groupname2\",\"subgroupname\":\"groupname0879200774654465\",\"rowlevel\":\"0\",\"conditionFieldVal\":\"dt\",\"conditionOptionVal\":\"greater_than\",\"conditionValueVal\":{\"value\":\"-200\",\"text\":\"-200\"},\"conditionValueLeftVal\":{\"value\":\"\",\"text\":\"\"},\"conditionValueRightVal\":{\"value\":\"\",\"text\":\"\"}},{\"logicalOperator\":\"and\",\"groupname\":\"groupname2\",\"subgroupname\":\"groupname4294845034540429\",\"rowlevel\":\"0\",\"conditionFieldVal\":\"stock\",\"conditionOptionVal\":\"equal\",\"conditionValueVal\":{\"value\":\"002236\",\"text\":\"002236\"},\"conditionValueLeftVal\":{\"value\":\"\",\"text\":\"\"},\"conditionValueRightVal\":{\"value\":\"\",\"text\":\"\"}}]&csrfmiddlewaretoken=OC16LAAquGsFWmfGyC2eXKy6HIUFX0oa6V9SSEwkA2lwJ6ZLRztGrYIgsEgw7t2A&sortField=dt&sortOrder=desc&isGroup=true&groupsortField=op&groupsortOrder=desc&groupCount=3";
            if (!StringUtils.isEmpty(jsonData)) {
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                out.write(jsonData);
                out.flush();
                out.close();
            }
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.info("connect failed! respCode:{}|respMsg:{}", conn.getResponseCode(), conn.getResponseMessage());
                return "";
            }
            //获取响应内容体
            StringBuffer sb = new StringBuffer();
            String readLine = new String();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine).append("\n");
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("doPost Http failed! " + e.getMessage());
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("sendGet close Exception:" + e2.getMessage());
            }
        }

        return "";



//
//        try {
//            HttpClient client = new HttpClient(); // 客户端实例化
//            PostMethod postMethod = new PostMethod(url); // 请求方法post，可以将请求路径传入构造参数中
//            postMethod.setRequestBody();
//
//
//            //postMethod.addRequestHeader("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJueDpwbHVnaW5fc2VydmVyOmFwaTpsb2dpbl90b2tlbnM6IjoiZDE4ZjFiNjgtNDAxOS00OWI2LWI4NWEtYjY1Y2ZjYjU0OGJmIn0.yx6vZZNNqIPDepvGaGea0hqCWNEAF_ftTL70mghajB3-QwHpxp2rmPnLHNvxE9YsjQMLgEk68MDsKvBzVMkIzg");
//            byte[] requestBytes = jsonData.getBytes("utf-8"); // 将参数转为二进制流
//
//            InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
//            // 请求体
//            RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
//            postMethod.setRequestEntity(requestEntity); // 将参数放入请求体
//            int i = client.executeMethod(postMethod); // 执行方法
//            System.out.println("请求状态" + i);
//
//            // 这里因该有判断的，根据请求状态判断请求是否成功，然后根据第三方接口返回的数据格式，解析出我们需要的数据
//            byte[] responseBody = postMethod.getResponseBody(); // 得到相应数据
//            String s = new String(responseBody);
//            System.out.println(s);
//        } catch (Exception e) {
//            System.out.println("发送 POST 请求出现异常！" + e);
//            e.printStackTrace();
//        } finally {
//            // 使用finally块来关闭输出流、输入流
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//
//        return result;
    }
    public static String getHtmlByPost(String urlString) throws IOException{
        /*
        * POST https://www.xxx.com
        sign: 3149fa619b03988963bf1c53b8947f0e
        Content-Type: application/x-www-form-urlencoded
        Content-Length: 285
        Host: www.xxx.com
        Connection: Keep-Alive
        Accept-Encoding: gzip
        User-Agent: okhttp/3.2.0
        _time=2017-12-15%2011%3A07%3A02&user_coordinate=116.307956%2C39.966622&coordinate=116.307956%2C39.966622&_osversion=6.0&radius=50000&_build=50&_platform=Android&_cityid=110100&_device=awiftb0%3A89%3A00%3A99%3A27%3Ae8&_version=3.8.3&page=1&channel=huijiachifan&size=10&_screen=1080x1810
        */
        URL url = new URL(urlString);
        //参数
        StringBuilder parameterbulider = new StringBuilder();
        //响应
        StringBuilder responseBuilder = new StringBuilder();
        BufferedReader reader = null;
        PrintWriter out = null;

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setInstanceFollowRedirects(false);
        //post 请求必须设置此处
        conn.setDoOutput(true);
        conn.setDoInput(true);

        conn.setUseCaches(false);
        conn.setDefaultUseCaches(false);
        conn.setConnectTimeout(30 * 1000);//连接超时
        conn.setReadTimeout(30 * 1000);//读取超市
        conn.setRequestMethod("POST");

        //多个参数拼接
        parameterbulider.append("sign=3149fa619b03988963bf1c53b8947f0e");
        parameterbulider.append("Content-Type=application/x-www-form-urlencoded");
        parameterbulider.append("Content-Length=285");
        parameterbulider.append("Host=www.xxx.com");
        parameterbulider.append("Connection=Keep-Alive");
        parameterbulider.append("Accept-Encoding=gzip");
        parameterbulider.append("User-Agent=okhttp/3.2.0");
        parameterbulider.append("_time=2017-12-15%2011%3A07%3A02&user_coordinate=116.307956%2C39.966622&coordinate=116.307956%2C39.966622&_osversion=6.0&radius=50000&_build=50&_platform=Android&_cityid=110100&_device=awiftb0%3A89%3A00%3A99%3A27%3Ae8&_version=3.8.3&page=2&channel=huijiachifan&size=10&_screen=1080x1810");


        out = new PrintWriter(conn.getOutputStream());
        out.print(parameterbulider.toString());
        out.flush();

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            responseBuilder.append(line + "\n");
        }
        reader.close();
        return responseBuilder.toString();
    }

    public static JSONObject getHttpJson(String url, int comefrom) throws Exception {
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            // 建立实际的连接
            connection.connect();
            //请求成功
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //10MB的缓存
                byte[] buffer = new byte[20485760];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                String jsonString = baos.toString("utf-8");
//                System.out.println(jsonString);
//                System.out.println(jsonString);
                baos.close();
                is.close();
                //转换成json数据处理
                // getHttpJson函数的后面的参数1，表示返回的是json数据，2表示http接口的数据在一个（）中的数据
                return getJsonString(jsonString, comefrom);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * GZIP解压字符串
     * 解决Content-Encoding: gzip 的问题
     * @param str 源字符串
     * @return
     * @throws IOException
     */
    public static String uncompressString(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str
                .getBytes("ISO-8859-1"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toString();
    }


//    public String test(String path) throws IOException {
//        URL url = new URL(path);
//        // 打开和url之间的连接
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        // PrintWriter out = null;
//        // 请求方式
//        conn.setRequestMethod("POST");
//        conn.setConnectTimeout(20000);
//        conn.setReadTimeout(20000);
//        // 设置通用的请求属性
//        conn.setRequestProperty("accept", "*/*");
//        conn.setRequestProperty("connection", "Keep-Alive");
//        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//        InputStream is = conn.getInputStream();
//        String contentType = conn.getContentType();
//        String contentEncoding = conn.getContentEncoding();
//        String result = "";
//        if ("gzip".equalsIgnoreCase(contentEncoding)) {
//            byte[] b = IOUtils.toByteArray(is);
//            ByteArrayInputStream bais = new ByteArrayInputStream(b);
//            GZIPInputStream gzis = new GZIPInputStream(bais);
//            InputStreamReader reader = new InputStreamReader(gzis);
//            BufferedReader in = new BufferedReader(reader);
//            String str = "";
//            while ((readed = in.readLine()) != null) {
//                result = str;
//                System.out.println("str:  " + str);
//            }
//        }else{
//            // 构造一个字符流缓存
//            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//            String str;
//            while ((str = br.readLine()) != null) {
//                result = str;
//                System.out.println("str:  " + str);
//            }
//        }
//        // 关闭流
//        is.close();
//        // 断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//        // 固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
//        conn.disconnect();
//        return result;
//
//    }

    public static JSONObject getJsonString(String str, int comefrom) throws Exception {
        JSONObject jo = null;
        if (comefrom == 1) {
            return JSONObject.parseObject(str);
        } else if (comefrom == 2) {
            int indexStart = 0;
            int indexEnd = 0;
            //字符处理
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '(') {
                    indexStart = i;
                }
                if (str.charAt(i) == ')') {
                    indexEnd = i;
                    break;
                }
            }
            StringBuilder strNew = new StringBuilder();
            //分割字符串
            for (int i = indexStart + 1; i < indexEnd; i++) {
                strNew.append(str.charAt(i));
            }
            return JSONObject.parseObject(strNew.toString());
        }
        return jo;
    }


    public PanKouInfoVo getPankouInfo(JSONObject jsonMap) {
        JSONArray result = jsonMap.getJSONArray("Result")
                                  .getJSONObject(1)
                                  .getJSONObject("DisplayData")
                                  .getJSONObject("resultData")
                                  .getJSONObject("tplData")
                                  .getJSONObject("result")
                                  .getJSONObject("minute_data")
                                  .getJSONObject("pankouinfos")
                                  .getJSONArray("list");
        PanKouInfoVo vo = new PanKouInfoVo();
        for (Object obj : result) {
            JSONObject jsObj = (JSONObject) obj;
            Field field = null;
            try {
                field = vo.getClass().getDeclaredField(jsObj.get("ename").toString());
                field.setAccessible(true);
                field.set(vo, jsObj.get("value").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return vo;
    }

    /**
     * 获取历史k线图
     * @param jsonMap
     * @return
     */
    public List<StockInfo> getKData(JSONObject jsonMap) {
        List<StockInfo> kLineList = new ArrayList<>();
        JSONArray result = jsonMap.getJSONArray("Result");
        result.forEach(vo -> {
//            System.out.println(vo.toString());
            if (vo.toString().length() > 10) {
                StockInfo kLineParseVo = new StockInfo();
                JSONObject jsonObject = JSONObject.parseObject(vo.toString());
                kLineParseVo.setRecordPt(DateUtils.parseDate((String)jsonObject.get("date")));

                kLineParseVo.setAmount((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("amount")).orElse("0")) * 100));
                kLineParseVo.setOpen((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("open")).orElse("0")) * 100));
                kLineParseVo.setHigh((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("high")).orElse("0")) * 100));
                kLineParseVo.setClose((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("close")).orElse("0")) * 100));
                kLineParseVo.setLow((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("low")).orElse("0")) * 100));
                kLineParseVo.setVolume((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("volume")).orElse("0")) * 100));
                kLineParseVo.setPreclose((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("preClose")).orElse("0")) * 100));
                kLineParseVo.setTurnoverratio((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("turnoverratio")).orElse("0")) * 100));
                kLineParseVo.setIncrease((int)(Double.parseDouble((String)Optional.ofNullable(jsonObject.getJSONObject("kline").get("increase")).orElse("0")) * 100));

                // 均线 * 100
                String ma5 = (String) Optional.ofNullable(jsonObject.getJSONObject("ma5").get("avgPrice")).orElse("0");
                if (Objects.nonNull(jsonObject.getJSONObject("ma5")) && StringUtils.isNotBlank(ma5)) {
                    kLineParseVo.setMa5((int)(Double.parseDouble(ma5) * 100));
                }
                String ma10 = (String) Optional.ofNullable(jsonObject.getJSONObject("ma10").get("avgPrice")).orElse("0");
                if (Objects.nonNull(jsonObject.getJSONObject("ma10")) && StringUtils.isNotBlank(ma10)) {
                    kLineParseVo.setMa10((int)(Double.parseDouble(ma10) * 100));
                }
                String ma20 = (String) Optional.ofNullable(jsonObject.getJSONObject("ma20").get("avgPrice")).orElse("0");
                if (Objects.nonNull(jsonObject.getJSONObject("ma20")) && StringUtils.isNotBlank(ma20)) {
                    kLineParseVo.setMa20((int)(Double.parseDouble(ma20) * 100));
                }
                kLineParseVo.setCreatedAt(new Date());
                kLineList.add(kLineParseVo);
//                System.out.println(JSONObject.toJSONString(kLineParseVo));
            }
        });

        return kLineList;
    }


    public static List<StockBasicVo> getStockBasic(JSONObject jsonMap) {
        List<StockBasicVo> list = new ArrayList<>();
        JSONArray result = jsonMap
                .getJSONObject("data").getJSONArray("diff");
        System.out.println("getStockBasic:" + jsonMap);
        for (int i = 0; i < result.size(); i++) {
            JSONObject jsonObject = result.getJSONObject(i);
            StockBasicVo stockBasicVo = new StockBasicVo();
            if (Objects.nonNull(jsonObject.get("f12"))) {
                stockBasicVo.setCode(jsonObject.get("f12").toString());
            }
            if (Objects.nonNull(jsonObject.get("f14"))) {
                stockBasicVo.setName(jsonObject.get("f14").toString());
            }
//            stockBasicVo.setExchange(jsonObject.get("exchange").toString());
            list.add(stockBasicVo);
        }
        return list;
    }


    public static List<StockBlock> getBlockInfo(JSONObject jsonMap) {
        List<StockBlock> blockList = Lists.newArrayList();

        JSONArray ssbk = jsonMap.getJSONArray("ssbk");

        for (int i = 0; i < ssbk.size(); i++) {
            JSONObject jsonObject = ssbk.getJSONObject(i);
            StockBlock stockBlock = new StockBlock();
            stockBlock.setStockCode((String)jsonObject.get("SECURITY_CODE"));
//            byte[] security_name_abbrs = ((String) jsonObject.get("SECURITY_NAME_ABBR")).getBytes();
//            stockBlock.setCompanyName(new String(security_name_abbrs, StandardCharsets.UTF_8));
            stockBlock.setCompanyName((String) jsonObject.get("SECURITY_NAME_ABBR"));
            stockBlock.setBoardCode((String)jsonObject.get("BOARD_CODE"));
            stockBlock.setBoardName((String) jsonObject.get("BOARD_NAME"));
//            byte[] board_names = ((String) jsonObject.get("BOARD_NAME")).getBytes();
//            stockBlock.setBoardName(new String(board_names, StandardCharsets.UTF_8));
            blockList.add(stockBlock);
        }

        return blockList;
    }

    public static List<StockCallAuctionInfo> getCallAuctionInfoList(JSONObject jsonMap) {
        List<StockCallAuctionInfo> infoList = Lists.newArrayList();
        JSONArray callAuctionList = jsonMap.getJSONArray("data");

        for (int i = 0; i < callAuctionList.size(); i++) {
            JSONObject jsonObject = callAuctionList.getJSONObject(i);
            StockCallAuctionInfo stockCallAuctionInfo = JSONObject.parseObject(String.valueOf(jsonObject), StockCallAuctionInfo.class);
//            stockCallAuctionInfo.setDown3();
//            stockCallAuctionInfo.setDown5();
//            stockCallAuctionInfo.setUp3();
//            stockCallAuctionInfo.setUp5();
//            stockCallAuctionInfo.setUp10();
//            stockCallAuctionInfo.setLowRk10();
//            stockCallAuctionInfo.setLowRk60();
//            stockCallAuctionInfo.setLowRk250();
//            stockCallAuctionInfo.setLow250();
//            stockCallAuctionInfo.setHigh5();
//            stockCallAuctionInfo.setHhigh5();
//            stockCallAuctionInfo.setHigh10();
//            stockCallAuctionInfo.setHigh20();
//            stockCallAuctionInfo.setHigh60();
//            stockCallAuctionInfo.setHighPre10();
//            stockCallAuctionInfo.setHighPre60();
//            stockCallAuctionInfo.setHighPre260();
        }

        return infoList;
    }
}
